package java8Com.chap2;

import org.omg.CORBA.PUBLIC_MEMBER;
import vo.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
　*
　*  行为参数传递
　*/
public class FilteringApples {

    public static void main(String[] args) {
        List<Apple> inventory = Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red"));
        List<Apple> apples = filterApple(inventory, new filterWeight());

        List<Apple> apples1 = filterApple(inventory, new ApplePredicate() {
            @Override
            public boolean test(Apple apple) {
                return "green".equals(apple.getColor());
            }
        });

        List<Apple> apples2 = filterApple(inventory, e -> {return e.getWeight() == 155;});
        apples2.forEach(x -> System.out.println(x.getWeight()));

        List<Apple> filter = filter(inventory, e -> e.getWeight() == 155);
        filter.forEach(x -> System.out.println(x.getWeight()));

    }

    interface ApplePredicate{
        public boolean test(Apple apple);
    }

    public static List<Apple> filterApple(List<Apple> list,ApplePredicate p){
        List<Apple> result = new ArrayList<>();
        list.forEach(e ->{
            if (p.test(e)){
                result.add(e);
            }
        });

        return result;
    }

    static class filterWeight implements ApplePredicate{

        @Override
        public boolean test(Apple apple) {
            return apple.getWeight()>15;
        }
    }

    //抽象
    public interface Predicate<T>{
        boolean test(T t);
    }

    public static <T> List<T> filter (List<T> list,Predicate<T> p){
        List<T> result = new ArrayList<>();
        list.forEach(e ->{
            if (p.test(e)){
                result.add(e);
            }
        });
        return result;
    }

}
